import { Component, OnInit } from '@angular/core';
import { FetchService } from '../../../../core/net/fetch.service';
import { NzMessageService } from 'ng-zorro-antd';
import * as moment from 'moment';
import { Observable } from 'rxjs';
import * as _ from 'lodash';

@Component({
    selector: 'app-dd-irr-area',
    templateUrl: './dd-irr-area.component.html',
    styleUrls: ['./dd-irr-area.component.scss']
})
export class DdIrrAreaComponent implements OnInit {
    contentTitle: string;
    today = new Date();
    detailData = [];
    tableTitle = '灌溉面积';
    widthConfig = ['200px', '180px', '180px', '180px', '180px', '180px', '180px', '180px', '180px'];
    isTableEditable = false;
    editCache: { [key: string]: { edit: boolean; data: any } } = {};

    constructor(private fetchService: FetchService,
                private message: NzMessageService) {
    }

    ngOnInit(): void {
        this.getTableRowsList().subscribe(res => {
            this.detailData = res['list'];
            this.getGridData();
        });
    }

    getTableRowsList(): Observable<any> {
        return this.fetchService.post('schedule/yjqPlanCropStructureIrrArea/list', {
            pageSize: 1000
        });
    }

    getGridData(): void {
        this.tableTitle = `${moment(this.today).year()}年${moment(this.today).month() + 1}月${moment(this.today).date()}日灌溉面积`;
        this.fetchService.post('schedule/yjqCropStructureIrrArea/list', {
            ctCreatetime: moment(this.today).format('YYYY-MM-DD'),
            pageSize: 1000
        }).subscribe(res => {
            this.detailData.forEach(row => {
                const data = _.find(res['list'], o => {
                    return o['cropId'] === row['id'];
                });
                row['cropId'] = row['cropId'] || row['id'];
                row['wheatDay'] = data ? data['wheatDay'] : null;
                row['riceDay'] = data ? data['riceDay'] : null;
                row['cornDay'] = data ? data['cornDay'] : null;
                row['otherTotalDay'] = data ? data['otherTotalDay'] : null;
                row['wheatTotal'] = data ? data['wheatTotal'] : null;
                row['riceTotal'] = data ? data['riceTotal'] : null;
                row['cornTotal'] = data ? data['cornTotal'] : null;
                row['otherTotalTotal'] = data ? data['otherTotalTotal'] : null;
            });
            this.updateEditCache();
        });
    }

    updateEditCache(): void {
        this.detailData.forEach(item => {
            this.editCache[item.id] = {
                edit: false,
                data: { ...item }
            };
        });
    }

    startEdit(): void {
        this.isTableEditable = true;
        this.detailData.forEach(item => {
            this.editCache[item.id] = {
                edit: false,
                data: { ...item }
            };
        });
        Object.keys(this.editCache).forEach(key => {
            //  跃进渠灌区 一所 二所 这三行不可编辑
            if (this.editCache[key]['pid'] !== '0' && this.editCache[key]['pid'] !== '8') {
                this.editCache[key].edit = true;
            }
        });
    }

    saveEditData(): void {
        this.detailData.forEach(item => {
            Object.assign(item, this.editCache[item.id].data);
            this.editCache[item.id].edit = false;
        });
        this.calcTotalRowsData();
        this.detailData.forEach(row => {
            row['ctCreatetime'] = moment(this.today).format('YYYY-MM-DD');
        });
        const params = this.detailData.map(item => {
            return _.pick(item, ['id', 'cropId', 'wheatDay', 'riceDay', 'cornDay', 'otherTotalDay', 'wheatTotal', 'riceTotal', 'cornTotal', 'otherTotalTotal', 'ctCreatetime']);
        });
        console.log(params);
        this.fetchService.post('schedule/yjqCropStructureIrrArea/batchAdd', params).subscribe(res => {
            this.isTableEditable = false;
            this.message.success('保存成功！');
            this.getGridData();
        });
    }

    resetEditData(): void {
        this.message.info('重置成功！');
        Object.keys(this.editCache).forEach((key, index) => {
            this.editCache[key].edit = false;
            this.editCache[key].data = { ...this.detailData[index] };
        });
    }

    cancelEdit(): void {
        this.isTableEditable = false;
        this.getGridData();
    }

    isRowEditable(row): boolean {
        return row.pid !== 0 && row.pid !== 8;
    }

    calcTotalRowsData(): any {
        //  一所、二所、跃进渠
        [9, 14, 8].forEach(pid => {
            const group = _.groupBy(this.detailData, 'pid')[pid];
            this.detailData.forEach(item => {
                if (item['cropId'] === pid) {
                    const keys = ['wheatDay', 'riceDay', 'cornDay', 'otherTotalDay', 'wheatTotal', 'riceTotal', 'cornTotal', 'otherTotalTotal'];
                    keys.forEach(key => {
                        item[key] = _.sum(group.map(o => {
                            return Number(o[key] || 0);
                        }));
                    });
                }
            });
        });
    }
}
